<!-- WordQuiz.vue -->
<template>
  <div class="word-quiz">
    <h3>单词选择题（共 {{ testCount }} 题）</h3>

    <div v-for="q in questions" :key="q.id" class="question" :id="q.id">
      <div class="question-text">
        <strong>{{ questions.indexOf(q) + 1 }}.</strong>
        <span class="word">{{ q.word }}</span><span v-if="q.type !== null">(</span><span v-if="q.type !== null">{{ q.type}}</span><span v-if="q.type !== null">)</span>
      </div>

      <!-- 选项单行显示 -->
      <div class="options">
        <button
            v-for="(opt, idx) in q.options"
            :key="idx"
            class="option"
            :class="{
            selected: userAnswers[q.id] === opt,
            correct: showResult && opt === q.correct,
            wrong: showResult && userAnswers[q.id] === opt && opt !== q.correct
          }"
            @click="selectOption(q.id, opt)"
            :disabled="showResult"
        >
          {{ String.fromCharCode(65 + idx) }}. {{ opt }}
        </button>
      </div>
    </div>

    <div class="actions">
      <button v-if="!showResult" @click="submit" class="btn-submit">
        提交答案
      </button>
    </div>

    <!-- 结果显示 -->
    <div v-if="showResult" class="result">
      <h4>
        答对 {{ correctNum }} / {{ testCount }} 题
      </h4>
      <p :style="{ color: accuracy >= 80 ? '#52c41a' : accuracy >= 60 ? '#faad14' : '#f5222d' }">
        正确率：{{ correctRate }}%
      </p>
    </div>
  </div>
</template>
<script setup>
import {ref, computed, getCurrentInstance} from 'vue'
import {getPageUnitTimes, insertDataToNewRecord} from "@/api/word/index.js";
import {addWordTest, getUsedTime} from "@/api/word/wordRecord.js";
import {renameKeys, shuffleArray, shuffleArrayLength} from "@/api/utils/index.js";
import {parseTime} from "@/utils/ruoyi.js";

// 定义 props
const props = defineProps({
  // 单词库
  wordParams: {
    type: Object,
    required: true
  },
  // 题目数量
  count: {
    type: Number,
    default: 30
  }
})

let practiceId = ref(null)
let testStartTime = ref(null)
let testEndTime = ref(null)
let testStartTimeStatus = ref(true)

// 定义 emit 事件
const emit = defineEmits(['finish'])
const testWord = ref({})
const testWordNum = ref({})
const testWordType = ref({})
const testCount = ref(0)
const correctNum = ref(0)
const correctRate = ref('')
let recordFrom = ref({})
const recordSubmit = ref({})
const {proxy} = getCurrentInstance();

let anotherData = ref([])
let anotherDataType = ref([])
let anotherDataTypeChinese = ref([])
let queryParamAnother = ref({
  unit: '',
  book: '',
  times: '1'
})

// 所有中文意思（用于生成干扰项）
const chineseWords = computed(() => Object.values(testWord.value))

// 生成题目
const questions = ref([])
const submitDataValue = ref([])
const userAnswers = ref({}) // 用户选择
const userTime = ref({})   // 用户点击时间
const showResult = ref(false)

// 打乱数组
const shuffle = (arr) => {
  const a = [...arr]
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[a[i], a[j]] = [a[j], a[i]]
  }
  return a
}

// 生成干扰项（3个错误选项）
const generateDistractors = (correct, all) => {
  return shuffle(all.filter(w => w !== correct)).slice(0, 3)
}

async function getWordList(){
  await getPageUnitTimes(props.wordParams).then((res) => {
    if (res.code === 200 && res.data !== undefined) {
      // console.log(res)
      let data = res.data
      // console.log(data.length)
      testWord.value = {}
      testWordNum.value = {}
      testWordType.value = {}
      data.forEach(item => {
        testWord.value[item.name] = item.chinese
        testWordNum.value[item.name] = item.number
        testWordType.value[item.name] = item.type
      })
      testCount.value = Object.keys(testWord.value).length
    }
  })
  await loadAnotherWord()
  initQuestions()
}

// 初始化题目
const initQuestions = () => {
  const wordList = Object.keys(testWord.value)
  const list = []

  for (let i = 0; i < testCount.value; i++) {
    const word = wordList[i]
    const correct = testWord.value[word]
    const type = testWordType.value[word]
    getSimilarData(type)
    const number = parseInt(testWordNum.value[word])
    const distractors = generateDistractors(correct, anotherDataTypeChinese.value)
    const options = shuffle([correct, ...distractors])

    list.push({
      id: `q${i}`,
      word,
      type,
      number,
      options,
      correct
    })
  }

  questions.value = shuffleArray(list)
  // console.log(questions.value)
  userAnswers.value = {}
  userTime.value = {}

  practiceId.value = Math.random().toString().substring(2)
  showResult.value = false
}


// 选择选项
const selectOption = (qid, option) => {
  userAnswers.value[qid] = option
  userTime.value[qid] = parseTime(new Date())
  //记录首次点击的时间
  if (testStartTimeStatus.value) {
    testStartTime.value = Date.now()
    testStartTimeStatus.value = false
  }
  // console.log(userAnswers.value)
}

// 提交测试
const submit = () => {
  // console.log(userAnswers.value)
  if(Object.keys(userAnswers.value).length === 0){
    proxy.$modal.msgError("未记录任何测试记录,请确认")
    return
  }
  let checkData = '还有未完成的测试'
  if(Object.keys(userAnswers.value).length === testCount.value){
    checkData = '您已完成所有的测试'
  }
  let confirmString = checkData +  ",是否确认提交?"
  proxy.$modal.confirm(confirmString).then(function () {
    testEndTime.value = Date.now()
    submitData()
    proxy.$modal.msgSuccess("提交成功")
  }).catch(() => {
    proxy.$modal.msg("取消提交")
  })
}


async function loadAnotherWord() {
  queryParamAnother.value.unit = null
  queryParamAnother.value.book = 'book' + Math.ceil(Math.random() * 6)
  await getPageUnitTimes(queryParamAnother.value).then((res) => {
    if (res.code === 200 && res.data !== undefined) {
      anotherData.value = res.data
      anotherData.value.forEach((item) => {
        delete item._id
        delete item.book
        delete item.unit
        delete item.number
      })
    }
  })
}

function getSimilarData(type) {
  type = type === null ? '' : type
  if (type.indexOf('+') > 0) {
    let number = Math.random() < 0.5 ? 0 : 1;
    type = type.split('+')[number]
  }
  if (type !== '') {
    if (type.toString().toLowerCase() === 'n' ||
        type.toString().toLowerCase() === 'v' ||
        type.toString().toLowerCase() === 'adj') {
      anotherDataType.value = anotherData.value.filter(item => {
        return item.type !== null && item.type.toLowerCase() === type.toLowerCase()
      })
      anotherDataType.value = shuffleArrayLength(anotherDataType.value,60)
    }
  } else {
    anotherDataType.value = anotherData.value.filter(item => {
      return item.type === null
    })
  }
  anotherDataTypeChinese.value = []
  anotherDataType.value.forEach(item => {
    anotherDataTypeChinese.value.push(item.chinese)
  })
}

function submitData(){
  correctNum.value = 0
  questions.value.forEach(q => {
    q['selected'] = userAnswers.value[q.id]
    q['practiceId'] = practiceId.value
    q['time'] = userTime.value[q.id]
    if (userAnswers.value[q.id] === q.correct) correctNum.value++
  })

  const accuracy = (correctNum.value / testCount.value) * 100
  correctRate.value = accuracy.toFixed(1)

  submitDataValue.value = []
  let keyMap = { word: "name",correct:"chinese"}
  for (let i = 0; i < questions.value.length; i++) {
    let keys = renameKeys(questions.value[i],keyMap);
    submitDataValue.value.push(keys)
  }

  // console.log(submitDataValue.value)

  recordSubmit.value['data'] = submitDataValue.value
  recordSubmit.value['book'] = props.wordParams.book

  recordSubmit.value['unit'] = props.wordParams.unit
  // 触发完成事件

  emit('finish', {
    correct: correctNum.value,
    total: testCount.value,
    accuracy: accuracy.toFixed(1) + '%'
  })

  insertDataToNewRecord(recordSubmit.value)

  //构建mysql数据
  recordFrom.value.book = props.wordParams.book
  recordFrom.value.unit = props.wordParams.unit
  recordFrom.value.times = props.wordParams.times
  recordFrom.value.practice = practiceId.value
  recordFrom.value.wordNum = testCount.value
  recordFrom.value.complete = Object.keys(userAnswers.value).length
  recordFrom.value.correctNum = correctNum.value
  recordFrom.value.way = 2
  recordFrom.value.usedTime =  getUsedTime((testEndTime.value - testStartTime.value) / 1000)
  recordFrom.value.correctRate = parseFloat(correctNum.value / testCount.value).toFixed(2)
  handleInsertRecordData(recordFrom.value)

  showResult.value = true
}

//连接MYSQL数据库-插入数据
function handleInsertRecordData(data) {
  // console.log(data)
  data.type = 'middle'
  addWordTest(data).then(res => {
    // console.log(res)
    recordFrom.value = {}
    testStartTimeStatus.value = true
  })
}

// 组件加载时初始化题目
getWordList()
</script>
<style scoped>
.word-quiz {
  font-family: 'Microsoft YaHei', sans-serif;
  max-width: 1200px;
  margin: 0 auto;
  background: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h3 {
  text-align: center;
  color: #1890ff;
  margin-bottom: 20px;
}

.question {
  margin: 18px 0;
  padding: 14px;
  background: #f9f9f9;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.question-text {
  font-size: 15px;
  margin-bottom: 10px;
  color: #333;
}

.word {
  color: #1890ff;
  font-size: 20px;
  font-weight: bold;
}

.options {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.option {
  flex: 1;
  padding: 8px 12px;
  background: #f0f8ff;
  border: 1px solid #91d5ff;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.option:hover:not(.selected):not(:disabled) {
  background: #91d5ff;
  color: white;
}

.option.selected {
  background: #1890ff;
  color: white;
  border-color: #1890ff;
}

.option.correct {
  background: #52c41a;
  color: white;
  border-color: #52c41a;
}

.option.wrong {
  background: #f5222d;
  color: white;
  border-color: #f5222d;
}

.option:disabled {
  cursor: not-allowed;
  opacity: 0.8;
}

.actions {
  text-align: center;
  margin: 20px 0;
}

.btn-submit {
  padding: 10px 24px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
}

.btn-submit:hover {
  background: #40a9ff;
}

.result {
  text-align: center;
  margin-top: 20px;
  font-weight: bold;
  font-size: 1.2em;
}
</style>